package nextEntity

import (
	"encoding/json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
)

type ConfEntity struct {
	BaseEntity *commEntity.BaseEntity // 基本信息

	Name string

	Data map[string]interface{}
}

type confPo struct {
	Id         int64 `json:"id" db:"id"`                  // 对象id
	CreateTime int64 `json:"createTime" db:"create_time"` // 创建时间
	UpdateTime int64 `json:"updateTime" db:"update_time"` // 更新时间

	Name string                 `json:"confName" db:"conf_name"` // 名称
	Data map[string]interface{} `json:"confData" db:"conf_data"` // 数据
}

func (e *ConfEntity) Type() string {
	return "ConfEntity"
}

func (e *ConfEntity) TableName() string {
	return "tb_conf"
}

func (e *ConfEntity) GetBaseEntity() *commEntity.BaseEntity {
	return e.BaseEntity
}

func (e *ConfEntity) Instance() *ConfEntity {
	return &ConfEntity{
		BaseEntity: new(commEntity.BaseEntity),
		Data:       make(map[string]interface{}),
	}
}

func (e *ConfEntity) NewEntity() commEntity.IEntity {
	return e.Instance()
}

func (e *ConfEntity) NewPo() interface{} {
	return &confPo{
		Data: make(map[string]interface{}),
	}
}

func (e *ConfEntity) MakeServiceKey() string {
	p := e.MakeServiceKeyList()
	return commEntity.MakeServiceKey(p)
}

func (e *ConfEntity) MakeServiceKeyList() []string {
	var p []string
	p = append(p, e.Name)
	return p
}

func (e *ConfEntity) BuildByJson(jsn *string) error {
	var po confPo
	err := json.Unmarshal([]byte(*jsn), &po)
	if err != nil {
		return err
	}

	e.BuildByPo(&po)
	return nil
}

func (e *ConfEntity) BuildToJson() (string, error) {
	po := e.BuildToPo()
	code, err := json.Marshal(po)
	if err != nil {
		return "", err
	}

	return string(code), nil
}

func (e *ConfEntity) BuildByPo(pop interface{}) {
	ptr := e
	po := pop.(*confPo)

	ptr.BaseEntity.Id = po.Id
	ptr.BaseEntity.CreateTime = po.CreateTime
	ptr.BaseEntity.UpdateTime = po.UpdateTime

	ptr.Data = po.Data
	ptr.Name = po.Name
}

func (e *ConfEntity) BuildToPo() interface{} {
	ptr := e
	po := confPo{}

	po.Id = ptr.BaseEntity.Id
	po.CreateTime = ptr.BaseEntity.CreateTime
	po.UpdateTime = ptr.BaseEntity.UpdateTime

	po.Data = ptr.Data
	po.Name = ptr.Name

	return &po
}
